package double_point;

/**
 * 2130.链表最大孪生和
 * 快慢指针+反转链表
 *
 * @author Api
 * @date 2023/10/6 11:51
 */
public class Code2130_MaximumTwinSumOfLinkedList {
    public int pairSum(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode head1 = head, head2 = reverse(slow);
        int res = 0;
        while (head2 != null) {
            res = Math.max(head1.val + head2.val, res);
            head1 = head1.next;
            head2 = head2.next;
        }
        return res;
    }


    private static ListNode reverse(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode curr = head;
        ListNode prev = null;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}


